package com.cskaoyan.mall.pay.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.mall.pay.constants.PayReturnCodeEnum;
import com.cskaoyan.mall.pay.dto.PaymentRequest;
import com.cskaoyan.mall.pay.dto.alipay.AlipayQueryRetResponse;
import com.cskaoyan.mall.pay.dto.alipay.AlipaymentResponse;
import com.cskaoyan.mall.pay.form.pay.PayForm;
import com.cskaoyan.mall.pay.service.PayCoreService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;

@RestController
@RequestMapping("/cashier")
@Slf4j
public class PayController {

    @Autowired
    PayCoreService payCoreService;


    @PostMapping("/pay")
    public ResponseData prePay(@RequestBody PayForm payForm, HttpServletRequest httpServletRequest) {
        log.info("支付表单数据:{}", payForm);
        PaymentRequest request = new PaymentRequest();
        String userInfo = (String) httpServletRequest.getHeader("user_info");
        JSONObject object = JSON.parseObject(userInfo);
        Long uid = object.getLong("uid");
        request.setUserId(uid);
        BigDecimal money = payForm.getMoney();
        request.setOrderFee(money);
        request.setPayChannel(payForm.getPayType());
        request.setSubject("csmall_order");
        //request.setSpbillCreateIp("115.195.125.164");
        request.setTradeNo(payForm.getOrderId());
        request.setTotalFee(money);

        AlipaymentResponse response = payCoreService.aliPay(request);
        if(response.getCode().equals(PayReturnCodeEnum.SUCCESS.getCode())){
            log.info("获取支付二维码成功，返回url");
            String qrCode = response.getQrCode();
            String codeUrl = "http://127.0.0.1:8099/image/" + qrCode;
            return new ResponseUtil<>().setData(codeUrl);
        }
        else {
            return new ResponseUtil<>().setErrorMsg(response.getMsg());
        }
    }


    @GetMapping("/queryStatus")
    public ResponseData checkPay(@RequestParam String orderId) {

        PaymentRequest paymentRequest = new PaymentRequest();
        paymentRequest.setTradeNo(orderId);

        AlipayQueryRetResponse response = payCoreService.queryAlipayRet(paymentRequest);
        if(response.getCode().equals(PayReturnCodeEnum.SUCCESS.getCode())){
            return new ResponseUtil<>().setData(null);
        }
        else {
            return new ResponseUtil<>().setErrorMsg(response.getMsg());
        }

    }


}
